package com.amose.handler;

import com.amose.config.Configuration;
import com.amose.config.Resource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.jboss.C3P0PooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.naming.NamingException;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author yangpeng
 * @time 2020/2/22
 * @since 1.0.0
 */
public class SqlMapConfigHandler {

    public Configuration parse(InputStream in) throws DocumentException, ClassNotFoundException, PropertyVetoException, NamingException {
        //读取sqlMapConfig.xml
        Document document = new SAXReader().read(in);
        //读取根路径
        Element root = document.getRootElement();
        Element dataSource = root.element("dataSource");
        List<Element> propertyList = dataSource.elements("property");
        Properties properties = new Properties();
        for(Element element : propertyList){
            properties.put(element.attributeValue("name"),element.attributeValue("value"));
        }
        //设置数据库配置信息
        Configuration configuration = new Configuration();
        ComboPooledDataSource c3P0PooledDataSource = new ComboPooledDataSource();
        c3P0PooledDataSource.setDriverClass(properties.getProperty("driver"));
        c3P0PooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        c3P0PooledDataSource.setUser(properties.getProperty("userName"));
        c3P0PooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(c3P0PooledDataSource);

        //解析mapper路径进行存储
        Element mappers = root.element("mappers");
        List<Element> mapperList = mappers.elements("mapper");
        SqlMapperHandler sqlMapperHandler = new SqlMapperHandler(configuration);
        for(Element mapper : mapperList){
            String mapperPath = mapper.attributeValue("resource");
            InputStream mapperInputStream = Resource.getResourceAsStream(mapperPath);
            sqlMapperHandler.parse(mapperInputStream);
        }
        return configuration;
    }
}
